package com.imooc.oa.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.function.Function;

//创建全局唯一的SqlSessionFactory对象
//mybatis获取SqLSession对象的工具类
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory=null;
    static {
        Reader reader=null;
        try {
            reader= Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            //初始化失败抛出异常
           throw new ExceptionInInitializerError(e);
        }

    }

    /**
     * 执行select查询sql
     * @param func 要执行查询语句的代码块，函数式接口lambda表达式
     * @return 查询结果
     */
    public static Object executeQuery(Function<SqlSession,Object> func)
    {
    SqlSession sqlSession=sqlSessionFactory.openSession();
    try{
    Object result=func.apply(sqlSession);
    return result;
    }
    finally {
        sqlSession.close();
    }
    }

    /**
     * 执行insert，update，delete写操作sql
     * @param func 要执行的写操作代码块，Function函数式接口，lambda表达式
     * @return 写操作后返回的结果x`
     * @throws Exception
     */
    public static Object executeUpdate(Function<SqlSession,Object> func)
    {
        //获得SqlSession对象，并将更新操作设置为手动提交事务
        SqlSession sqlSession=sqlSessionFactory.openSession(false);
        try{
            Object result=func.apply(sqlSession);
            sqlSession.commit();
            return  result;
        }
        catch (RuntimeException e){
            sqlSession.rollback();
            throw e;
        }finally {
            sqlSession.close();
        }
    }
}
